package com.lb.activity.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lb.activity.mapper.WebArticleCommentMapper;
import com.lb.activity.mapper.WebArticleMapper;
import com.lb.activity.po.WebArticle;
import com.lb.activity.po.WebArticleComment;
import com.lb.activity.service.TextService;
import com.lb.activity.util.JsonUtil;
import com.lb.activity.util.ResultUtil;
import com.lb.activity.util.SnowflakeIdWorker;
import com.lb.activity.util.emumdata.DataEnum;
import com.lb.activity.vo.ArticleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author 001030
 */
@Service
public class TextServiceImpl implements TextService {


    @Autowired
    private WebArticleMapper webArticleMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SnowflakeIdWorker idWorker;

    @Autowired
    private WebArticleCommentMapper webArticleCommentMapper;


    @Override
    public Map<String, Object> restTexts(Integer page) {
        if(page == null){
            page = 1;
        }
        PageHelper.startPage(page,2);
        Example example = new Example(WebArticle.class);
        Example.Criteria criteria = example.createCriteria();
        //正常状态的文章
        criteria.andEqualTo("status", DataEnum.INSERT_STATUS.getStatus());
        //按照创建时间排序
        example.setOrderByClause(" create_time desc ");
        List<WebArticle> webArticles = webArticleMapper.selectByExample(example);
        List list = new ArrayList();
        webArticles.forEach(art -> {
            Map<String,Object> map = new ConcurrentHashMap();
            map.put("title",art.getArtTitle());
            map.put("desc",art.getArtDesc());
            try {
                map.put("content",new String(art.getArtContent(),"utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            map.put("id",art.getId());
            map.put("label",art.getArtLabel());
            map.put("lableText",art.getArtLabelText());
            map.put("readCount",art.getArtReadCount());
            map.put("like",art.getArtLike());
            map.put("createTime",art.getCreateTime());
            map.put("artComment",art.getArtComment());
            list.add(map);
        });
        //返回值
        PageInfo<ArticleVo> pageInfo = new PageInfo(webArticles);
        Map<String, Object> map = new ConcurrentHashMap<>(2);
        Object topAct = redisTemplate.opsForValue().get("topAct");
        WebArticle webArticle = JsonUtil.jsonToPojo(topAct.toString(), WebArticle.class);
        //总页数
        map.put("total",pageInfo.getTotal());
        //数据
        map.put("data",list);
        map.put("top",webArticle);
        return map;
    }

    @Override
    public ArticleVo showData(Long id) {
        WebArticle webArticle = webArticleMapper.selectByPrimaryKey(id);
        ArticleVo articleVo = ArticleVo.builder().build();
        BeanUtils.copyProperties(webArticle,articleVo);
        try {
            articleVo.setContent(new String(webArticle.getArtContent(),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return articleVo;
    }

    @Override
    public void syncData() {
        Example example = new Example(WebArticle.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status", DataEnum.INSERT_STATUS.getStatus());
        criteria.andEqualTo("isTop", DataEnum.DATA_TOP.getStatus());
        List<WebArticle> topAct = webArticleMapper.selectByExample(example);
        example.clear();
        Example.Criteria criteria1 = example.createCriteria();
        criteria1.andEqualTo("status", DataEnum.INSERT_STATUS.getStatus());
        criteria1.andEqualTo("isHot", DataEnum.DATA_HOT.getStatus());
        List<WebArticle> hotAct = webArticleMapper.selectByExample(example);
        if(topAct != null){
            try {
                redisTemplate.opsForValue().set("topAct",JsonUtil.objectToJson(topAct.get(0)));
                redisTemplate.opsForValue().set("hotAct",JsonUtil.objectToJson(hotAct));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public List<ArticleVo> arts() {
        List<WebArticle> articles = JsonUtil.jsonToList(redisTemplate.opsForValue().get("hotAct").toString(), WebArticle.class);
        List<ArticleVo> list = new ArrayList<>();
        articles.forEach(art -> {
            ArticleVo articleVo = ArticleVo.builder().build();
            BeanUtils.copyProperties(art,articleVo);
            try {
                articleVo.setContent(new String(art.getArtContent(),"utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            list.add(articleVo);
        });
        return list;
    }

    @Override
    public ResultUtil addComment(WebArticleComment webArticleComment) {
        webArticleComment.setId(idWorker.nextId());
        int i = webArticleCommentMapper.insertSelective(webArticleComment);
        if(i > 0){
            //操作文章评论个数
            WebArticle webArticle = webArticleMapper.selectByPrimaryKey(webArticleComment.getActId());
            webArticle.setArtComment(webArticle.getArtComment()+1);
            webArticleMapper.updateByPrimaryKeySelective(webArticle);
            return ResultUtil.ok();
        }else {
            return ResultUtil.build(400,"添加失败");
        }
    }

    @Override
    public ResultUtil comments(Long actId) {
        Example example = new Example(WebArticleComment.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",DataEnum.INSERT_STATUS.getStatus());
        criteria.andEqualTo("actId",actId);
        List<WebArticleComment> webArticleComments = webArticleCommentMapper.selectByExample(example);
        return ResultUtil.ok(webArticleComments);
    }

    @Override
    public ResultUtil hotCommentAct() {
        Example example = new Example(WebArticle.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status", DataEnum.INSERT_STATUS.getStatus());
        example.setOrderByClause("update_time desc,art_comment desc");
        List<WebArticle> articles = webArticleMapper.selectByExample(example);
        return ResultUtil.ok(articles);
    }
}
